<template>
  <div class="container">
    <!-- 顶部选项卡 -->
    <div class="tabs-header">
      <van-tabs
        v-model:active="showTab"
        title-active-color="#000"
        color="#000"
        title-inactive-color="#999"
        @click-tab="handleShowTab"
        shrink
      >
        <van-tab
          v-for="(item, index) in headerList"
          :name="parseInt(item.dictValue)"
          :key="index"
        >
          <template #title>
            <div v-if="item.status == 0" class="tab-title">
              {{ _t18(item.dictLabel) }}
            </div>
          </template>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 币种内容 -->
    <div class="currency-list">
      <!-- ✅ 公用 banner（从接口加载，可轮播） -->
      <div v-if="!props.showAll && bannerList.length" class="carousel-banner">
        <van-swipe
          v-if="bannerList.length > 1"
          :autoplay="3000"
          lazy-render
          :loop="true"
          :show-indicators="false"
        >
          <van-swipe-item v-for="(item, index) in bannerList" :key="index">
            <image-load
              :filePath="item.imgUrl"
              alt="banner"
              class="banner-img"
              @click="linkToBanner(item)"
            />
          </van-swipe-item>
        </van-swipe>

        <template v-else>
          <image-load
            :filePath="bannerList[0].imgUrl"
            alt="banner"
            class="banner-img"
            @click="linkToBanner(bannerList[0])"
          />
        </template>
      </div>
      <!-- tab 内容 -->
      <template v-if="showTab === 1">
        <SectionHeader v-if="!props.showAll" :title="headerList[1]?.dictLabel" />
        <CurrencyCardList :list="mockCurrencyList" :tab-index="showTab" />
      </template>

      <template v-if="showTab === 2">
        <SectionHeader v-if="!props.showAll" :title="headerList[0]?.dictLabel" />
        <CurrencyCardList :list="mockCurrencyList" :tab-index="showTab" />
        <CustomTabsBlock
          v-if="!props.showAll"
          v-model="customTabIndex"
          :tabs="customTabs"
          :aiQuantList="aiQuantList"
          ai-quant-main-icon="/static/img/zIO_fc482b0e_j1z.1db64704.png"
          :ai-quant-title="t('ai_quant_title')"
          :ai-quant-subtitle="t('ai_quant_subtitle')"
          :ai-quant-apply-text="t('ai_quant_apply')"
          :arbitrage-list="arbitrageList"
          arbitrage-rate-up-icon="/static/images-ai/cHb_86f23530_Ecq.svg"
          arbitrage-rate-down-icon="/static/images-ai/V28_37739625_Pvd.svg"
          :arbitrage-volume-text="t('arbitrage_24h_volume')"
          :arbitrage-fluctuation-text="t('arbitrage_fluctuation')"
          :arbitrage-buy-price-text="t('arbitrage_buy_price')"
          :arbitrage-btn-text="t('arbitrage_btn')"
          :market-list="mockCurrencyList"
          @arbitrageAction="arbitrageAction"
        >
          <template #currency-card-list>
            <CurrencyCardList :list="mockCurrencyList" />
          </template>
        </CustomTabsBlock>
      </template>

      <template v-if="showTab === 3">
        <SectionHeader v-if="!props.showAll" :title="headerList[3]?.dictLabel" />
        <CurrencyCardList :list="mockCurrencyList" :tab-index="showTab" />
      </template>

      <template v-if="showTab === 4">
        <SectionHeader v-if="!props.showAll" :title="headerList[2]?.dictLabel" />
        <CurrencyCardList :list="mockCurrencyList" :tab-index="showTab" />
      </template>

      <template v-if="showTab === 5">
        <SectionHeader v-if="!props.showAll" :title="headerList[4]?.dictLabel" />
        <CurrencyCardList :list="mockCurrencyList" :tab-index="showTab" />
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTradeStore } from '@/store/trade'
import { useMainStore } from '@/store'
import { _t18 } from '@/utils/public'
import SectionHeader from './SectionHeader.vue'
import CurrencyCardList from './CurrencyCardList.vue'
import { useI18n } from 'vue-i18n'
import CustomTabsBlock from './CustomTabsBlock.vue'
import { dict, publiceNotice } from '@/api/common'

const props = defineProps({
  showAll: {
    type: Boolean,
    default: false
  }
})

const { t } = useI18n()
const tradeStore = useTradeStore()
const mainStore = useMainStore()
const router = useRouter()

const showTab = ref(['ebc'].includes(__config._APP_ENV) ? 1 : 0)
const customTabIndex = ref(0)
const customTabs = computed(() => [t('ai_tab_contract'), t('ai_tab_option')])
const headerList = ref([])
const bannerList = ref([])

/** 获取币种分类 */
const getDict = async () => {
  const res = await dict('t_second_coin_type')
  if (res.code == '200') headerList.value = res.data
}

/** 获取 banner 图 */
const getBannerList = async () => {
  try {
    const res = await publiceNotice('ACTIVITY_NOTICE', 'HOME_ACTIVITY ')
    if (res.code === 200) {
      bannerList.value = res.data.filter((item) => item.status != '1')
    }
  } catch (e) {
    console.error('获取 banner 失败:', e)
  }
}

/** banner 点击跳转 */
const linkToBanner = (item) => {
  if (item.noticeContent && item.noticeContent !== '<p><br></p>') {
    router.push(`/broadcastDetails?id=${item.noticeId}`)
  } else if (item.detailUrl) {
    router.push(item.detailUrl)
  }
}

/** tab 切换 */
const handleShowTab = (tab) => {
  showTab.value = parseInt(tab.name)
}

function genChartData(base = 100, count = 20) {
  let arr = [base]
  for (let i = 1; i < count; i++) {
    let next = arr[i - 1] + (Math.random() - 0.5) * base * 0.7
    arr.push(Number(next.toFixed(2)))
  }
  return arr
}

function genRandomPoints(count = 20, width = 80, height = 32) {
  const step = width / (count - 1)
  let value = Math.random() * height
  const points = []
  for (let i = 0; i < count; i++) {
    value += (Math.random() - 0.5) * (height / 5)
    value = Math.min(Math.max(value, 0), height)
    points.push(`${i * step},${height - value}`)
  }
  return points.join(' ')
}

const mockCurrencyList = computed(() =>
  tradeStore.secondContractCoinList
    .filter((it) => it.coinType === showTab.value)
    .slice(0, 4)   // ⭐ 只取前 10 条
    .map((item) => ({
      ...item,
      chartData: genChartData(100, 20),
      line: genRandomPoints()
    }))
)

console.log(tradeStore.secondContractCoinList)
const arbitrageList = [
  {
    id: 1,
    icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/949bc8d1f5d1491d8f2d57e07cf553e2.png',
    title: 'Huobi',
    volume: '227348674.042065',
    rate: -0.34,
    price: '117228.732'
  }
]

function arbitrageAction(item) {
  alert('套利平台: ' + item.title)
}

onMounted(() => {
  getDict()
  getBannerList()
})
</script>

<style lang="scss" scoped>
// 完整CSS代码
.container {
  /* 动态计算容器高度（100vh - 底部导航栏高度） */
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;

  .tabs-header {
    margin-top: 10px;
    :deep(.van-tabs__nav) {
      background: transparent !important;
    }
    :deep(.tab-title) {
      padding: 6px 3px;
      font-size: 14px !important;
      font-weight: 500;
      border-radius: 18px;
      transition: all 0.2s;
    }
    :deep(.van-tab--active) {
      font-weight: 600;
      font-size: 18px !important;
    }
  }
  .currency-list-item {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* 一行 3 列 */
    gap: 20px; /* 列和行之间的间距 */
  }
  .currency-list {
    flex: 1;
    min-height: 0; /* 允许内容区域收缩 */
    overflow-y: auto;
    /* 增加底部安全间距（80px为底部导航高度） */
    padding: 12px 16px calc(80px + env(safe-area-inset-bottom));
    box-sizing: border-box;

    /* 滚动优化 */
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;

    ::v-deep(.currency-item) {
      background: #12161f;
      border-radius: 8px;
      margin-bottom: 8px;
      padding: 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      > div:first-child {
        flex: 1;
        max-width: 60%;
      }

      > div:last-child {
        flex: none;
        text-align: right;
      }
    }
  }
}

.carousel-banner {
  width: 100%;
  margin: 0 auto 12px auto;
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px;
  img {
    width: 100%;
    display: block;
    border-radius: 14px;
    object-fit: cover;
    min-height: 180px;
    background: #f5f5f5;
  }
}

/* 全局底部导航栏样式（需要与实际项目匹配） */
.global-bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  /* 兼容全面屏设备 */
  padding-bottom: env(safe-area-inset-bottom);
  background: #1a1e25;
  z-index: 1000;
}

/* 删除与币种卡片相关的所有样式（如.currency-card-custom、.card-header-custom等） */

.ai-bottom-tab {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  background: #f6f7f9;
  gap: 12px;
}
.tab-btn {
  font-size: 13px;
  font-weight: 600;
  border-radius: 20px;
  padding: 10px;
  color: #111;
  transition: all 0.2s;
}
.tab-btn-active {
  background: #111;
  color: #fff;
}
.ai-sub-tab {
  display: flex;
  align-items: center;
  background: #f6f7f9;
  padding: 0 0 0 16px;
  gap: 24px;
  height: 40px;
}
.sub-tab-btn {
  font-size: 15px;
  font-weight: 600;
  color: #999;
  position: relative;
  cursor: pointer;
}
.sub-tab-btn-active {
  color: #111;
}
.sub-tab-underline {
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 100%;
  height: 3px;
  background: #111;
  border-radius: 2px;
}
.ai-sub-tab-van {
  :deep(.van-tabs__nav) {
    background: transparent;
  }
}
.ai-card-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin: 18px 0 0 0;
}
.ai-card-item {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 18px 18px 18px 14px;
  position: relative;
}
.ai-card-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 14px;
  background: #f5f5f5;
}
.ai-card-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.ai-card-name {
  font-size: 17px;
  font-weight: 700;
  color: #222;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ai-card-desc {
  font-size: 13px;
  color: #888;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ai-card-profit-label {
  font-size: 14px;
  color: #222;
  margin-top: 2px;
}
.ai-card-arrow {
  width: 22px;
  height: 22px;
  margin-left: 10px;
}
</style>
